package utils

import (
	"errors"
	"finance/config"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

type Claims struct {
	UserID               uint   `json:"user_id"`
	Username             string `json:"username"`
	RoleID               uint   `json:"role_id"`
	RoleName             string `json:"role_name"`
	jwt.RegisteredClaims        // JWT 库提供的标准字段，比如：ExpiresAt, IssusedAt, Issuer
}

func GenerateToken(userID uint, username string, roleName string, roleID uint) (string, error) {
	jwtSecret := config.AppConfig.Jwt.Secret
	expire := time.Hour * time.Duration(config.AppConfig.Jwt.Expire)

	claims := Claims{
		UserID:   userID,
		Username: username,
		RoleName: roleName,
		RoleID:   roleID,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(expire)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			Issuer:    "bank_system",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(jwtSecret))
}

func ParseToken(tokenStr string) (*Claims, error) {
	jwtSecret := config.AppConfig.Jwt.Secret
	token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(jwtSecret), nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	}
	return nil, errors.New("invalid token")
}
